package com.itboye.jinpuyiyuan.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.mobileim.IYWLoginService;
import com.alibaba.mobileim.IYWUIPushListener;
import com.alibaba.mobileim.YWAPI;
import com.alibaba.mobileim.YWIMCore;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.YWLoginParam;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.alibaba.mobileim.channel.util.WxLog;
import com.alibaba.mobileim.channel.util.YWLog;
import com.alibaba.mobileim.conversation.IYWConversationService;
import com.alibaba.mobileim.conversation.IYWConversationUnreadChangeListener;
import com.alibaba.mobileim.conversation.IYWMessageLifeCycleListener;
import com.alibaba.mobileim.conversation.IYWMessageListener;
import com.alibaba.mobileim.conversation.IYWSendMessageToContactInBlackListListener;
import com.alibaba.mobileim.conversation.YWConversation;
import com.alibaba.mobileim.conversation.YWConversationType;
import com.alibaba.mobileim.conversation.YWMessage;
import com.alibaba.mobileim.conversation.YWMessageChannel;
import com.alibaba.mobileim.conversation.YWMessageType;
import com.alibaba.mobileim.gingko.model.tribe.YWTribe;
import com.alibaba.mobileim.gingko.model.tribe.YWTribeMember;
import com.alibaba.mobileim.gingko.presenter.tribe.IYWTribeChangeListener;
import com.alibaba.mobileim.login.IYWConnectionListener;
import com.alibaba.mobileim.login.YWLoginCode;
import com.alibaba.mobileim.login.YWLoginState;
import com.alibaba.mobileim.utility.IMNotificationUtils;
import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.activity.login.LoginActivity;
import com.itboye.jinpuyiyuan.activity.login.LoginOrRegisterActivity;
import com.itboye.jinpuyiyuan.activity.message.ServerFragment;
import com.itboye.jinpuyiyuan.adapter.MessagePagerAdapter;
import com.itboye.jinpuyiyuan.app.MyApplication;
import com.itboye.jinpuyiyuan.base.BaseFragment;
import com.itboye.jinpuyiyuan.presenter.BranchAddressPresenter;
import com.itboye.jinpuyiyuan.utils.IMKit.CustomConversationHelper;
import com.itboye.jinpuyiyuan.utils.IMKit.LoginSampleHelper;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.FilterUtil;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by Administrator on 2017/12/5 0005.
 */

public class MessageFragment extends BaseFragment implements Observer {
    private ViewPager messageVP;
    private TextView tvGood,tvServer;
    private ImageView line;
    private boolean isMeasured=false;

    public static final String TAG = "MessageFragment";
    //line 滑动距离
    private int instance ;
    private int currIndex;//当前的停留的页数


    private ServerFragment serverFragment;

    private Fragment conversationFragment;

    private YWIMKit mIMKit;
    private IYWConversationService mConversationService;
    private Handler mHandler = new Handler(Looper.getMainLooper());

    private IYWTribeChangeListener mTribeChangedListener;
    private IYWConversationUnreadChangeListener mConversationUnreadChangeListener;
    private IYWMessageLifeCycleListener mMessageLifeCycleListener;
    private IYWSendMessageToContactInBlackListListener mSendMessageToContactInBlackListListener;
    private IYWConnectionListener mConnectionListener;

    public static final String SYSTEM_TRIBE_CONVERSATION="sysTribe";
    public static final String SYSTEM_FRIEND_REQ_CONVERSATION="sysfrdreq";
    public static final String RELATED_ACCOUNT = "relatedAccount";
    private String userid;//阿里百川id
    private String password;//阿里百川user password
    private String uid;//用户uid
    private YWIMCore imCore;
    private int id;//分辨患者和医生

    private MessagePagerAdapter messagePagerAdapter;
    private ArrayList<Fragment> list;
    
    private BranchAddressPresenter presenter;
    @Override
    public int initView() {
        return R.layout.fragment_message;

    }

    @Override
    public void onMyActivityCreated() {
    //同步头像和密码用户聊天头像的设定（后台接口设置）
        id= (int) SPUtils.get(getActivity().getApplication(),null,"roles_doctor",0);
        uid= (String) SPUtils.get(getActivity().getApplication(),null,Const.UID,"");
        presenter = new BranchAddressPresenter(this);
        presenter.synPersonInfo(uid);
        initIMkitData();
        conversationFragment = mIMKit.getConversationFragment();
        serverFragment=new ServerFragment();

        list=new ArrayList<>();
        list.add(conversationFragment);
        list.add(serverFragment);
        messagePagerAdapter=new MessagePagerAdapter(getChildFragmentManager(),list);
        messageVP.setAdapter(messagePagerAdapter);
        currIndex=0;


              ViewTreeObserver observer = tvGood.getViewTreeObserver();
              observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                  public boolean onPreDraw() {
                      if (!isMeasured) {
                          int layoutHeight = tvGood.getWidth();
                          Log.d("=======",layoutHeight+"");
                          instance=tvServer.getLeft();
                          Log.d("=======",instance+"");
                          RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(layoutHeight,4);
                          params.addRule(RelativeLayout.BELOW,R.id.llTable);
                          params.addRule(RelativeLayout.ALIGN_LEFT,R.id.llTable);
                          line.setLayoutParams(params);
                          isMeasured = true;
                      }
                      return true;
                  }
              });

              messageVP.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                  @Override
                  public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                  }

                  @Override
                  public void onPageSelected(int position) {
                      cancleTableState();
                      if (position==0){
                          tvGood.setTextColor(getActivity().getResources().getColor(R.color.title_blue));

                      }else {
                          tvServer.setTextColor(getActivity().getResources().getColor(R.color.title_blue));
                      }
                      tranSlate(position,300);
                      currIndex=position;
                  }

                  @Override
                  public void onPageScrollStateChanged(int state) {

                  }
              });

    }


    public void initIMkitData(){
        userid= (String) SPUtils.get(getActivity().getApplication(),null,Const.ALIBAICHUAN,"");
        Log.d("userid==",""+userid);
        password= (String) SPUtils.get(getActivity().getApplication(),null,Const.PASSWORD,"");
//初始化imkit
        mIMKit = YWAPI.getIMKitInstance(userid,Const.OPEN_APPKEY);

        LoginSampleHelper.getInstance().initIMKit(userid, Const.OPEN_APPKEY);

        imCore=mIMKit.getIMCore();

        Log.d("====mIMKit",mIMKit.toString()+mIMKit.getAppName());

        mConversationService = mIMKit.getConversationService();

//        initListeners();


    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        Log.d("=======",tvGood.getWidth()+"");
//    }



    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvGood:

                cancleTableState();
            tvGood.setTextColor(getActivity().getResources().getColor(R.color.title_blue));
                messageVP.setCurrentItem(0);
                break;
            case R.id.tvServer:
            cancleTableState();
            tvServer.setTextColor(getActivity().getResources().getColor(R.color.title_blue));
            messageVP.setCurrentItem(1);
                break;
        }
    }


    /**
     * 平移动画
     *
     * @param currentItem
     * @param durationMillis
     */
    public void tranSlate(int currentItem, long durationMillis) {
        float one = instance;
        Log.v("offest", "" + instance);
        Animation animation = new TranslateAnimation(currIndex * one,
                currentItem * one, 0, 0);// 平移动画
        Log.v("currentoffest", "" + currIndex * one);
        Log.v("currentItem", "" + currentItem * one);
        animation.setFillAfter(true);// 动画终止时停留在最后一帧，不然会回到没有执行前的状态
        animation.setDuration(durationMillis);// 动画持续时间0.2秒
        line.startAnimation(animation);// 是用ImageView来显示动画的
    }
    /**
     * 清除table textview颜色
     *
     */
    public void cancleTableState(){
        tvGood.setTextColor(getActivity().getResources().getColor(R.color.black));
        tvServer.setTextColor(getActivity().getResources().getColor(R.color.black));

    }



    /**
     * 初始化相关监听
     */
    private void initListeners(){
//        //初始化并添加会话变更监听
        initConversationServiceAndListener();
//        //初始化并添加群变更监听
//        addTribeChangeListener();
//        //初始化自定义会话
//        initCustomConversation();
        //设置发送消息生命周期监听
        setMessageLifeCycleListener();
        //设置发送消息给黑名单中的联系人监听
        setSendMessageToContactInBlackListListener();
        //添加IM连接状态监听
        addConnectionListener();

        //新消息通知的回调
    }

    /**
     * 自定义会话示例展示系统通知的示例
     */
    private void initCustomConversation() {
        CustomConversationHelper.addCustomConversation(SYSTEM_FRIEND_REQ_CONVERSATION, null);
    }

    private void initConversationServiceAndListener() {
        mConversationUnreadChangeListener = new IYWConversationUnreadChangeListener() {

            //当未读数发生变化时会回调该方法，开发者可以在该方法中更新未读数
            @Override
            public void onUnreadChange() {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        LoginSampleHelper loginHelper = LoginSampleHelper.getInstance();
                        final YWIMKit imKit = loginHelper.getIMKit();
                        if (imKit==null){
                            Log.d("===imkit","shide");
                        }else {
                            Log.d("===imkit","meiyou");
                        }
                        mConversationService = imKit.getConversationService();
                        //获取当前登录用户的所有未读数
                        int unReadCount = mConversationService.getAllUnreadCount();
                        //设置桌面角标的未读数
                        mIMKit.setShortcutBadger(unReadCount);
                    }
                });
            }
        };
        mConversationService.addTotalUnreadChangeListener(mConversationUnreadChangeListener);
    }

    private void addTribeChangeListener(){
        mTribeChangedListener = new IYWTribeChangeListener() {
            @Override
            public void onInvite(YWTribe tribe, YWTribeMember user) {
                Map<YWTribe, YWTribeMember> map = new HashMap<YWTribe, YWTribeMember>();
                map.put(tribe, user);
                LoginSampleHelper.getInstance().getTribeInviteMessages().add(map);
                String userName = user.getShowName();
                if (TextUtils.isEmpty(userName)){
                    userName = user.getUserId();
                }
                WxLog.i(TAG, "onInvite");
            }

            @Override
            public void onUserJoin(YWTribe tribe, YWTribeMember user) {
                //用户user加入群tribe
            }

            @Override
            public void onUserQuit(YWTribe tribe, YWTribeMember user) {
                //用户user退出群tribe
            }

            @Override
            public void onUserRemoved(YWTribe tribe, YWTribeMember user) {
                //用户user被提出群tribe
            }

            @Override
            public void onTribeDestroyed(YWTribe tribe) {
                //群组tribe被解散了
            }

            @Override
            public void onTribeInfoUpdated(YWTribe tribe) {
                //群组tribe的信息更新了（群名称、群公告、群校验模式修改了）
            }

            @Override
            public void onTribeManagerChanged(YWTribe tribe, YWTribeMember user) {
                //用户user被设置为群管理员或者被取消管理员
            }

            @Override
            public void onTribeRoleChanged(YWTribe tribe, YWTribeMember user) {
                //用户user的群角色发生改变了
            }
        };
        mIMKit.getTribeService().addTribeListener(mTribeChangedListener);
    }

    private void setMessageLifeCycleListener(){
        mMessageLifeCycleListener = new IYWMessageLifeCycleListener() {
            /**
             * 发送消息前回调
             * @param conversation 当前消息所在会话
             * @param message      当前将要发送的消息
             * @return  需要发送的消息，若为null，则表示不发送消息
             */
            @Override
            public YWMessage onMessageLifeBeforeSend(YWConversation conversation, YWMessage message) {

                Log.d("Message==",message.toString());
                //todo 以下代码仅仅是示例，开发者无需按照以下方式设置，应该根据自己的需求对消息进行修改
                String cvsType = "单聊";
                if (conversation.getConversationType() == YWConversationType.Tribe){
                    cvsType = "群聊：";
                }
                String msgType = "文本消息";
                if (message.getSubType() == YWMessage.SUB_MSG_TYPE.IM_IMAGE){
                    msgType = "图片消息";
                } else if (message.getSubType() == YWMessage.SUB_MSG_TYPE.IM_GEO){
                    msgType = "地理位置消息";
                } else if (message.getSubType() == YWMessage.SUB_MSG_TYPE.IM_AUDIO){
                    msgType = "语音消息";
                } else if (message.getSubType() == YWMessage.SUB_MSG_TYPE.IM_P2P_CUS || message.getSubType() == YWMessage.SUB_MSG_TYPE.IM_TRIBE_CUS){
                    msgType = "自定义消息";
                }

                //TODO 设置APNS Push，如果开发者需要对APNS Push进行定制可以调用message.setPushInfo(YWPushInfo)方法进行设置，如果不需要APNS Push定制则不需要调用message.setPushInfo(YWPushInfo)方法
                //TODO Demo默认发送消息不需要APNS Push定制,所以注释掉以下两行代码
//                YWPushInfo pushInfo = new YWPushInfo(1, cvsType + msgType, "dingdong", "我是自定义数据");
//                message.setPushInfo(pushInfo);

                //根据消息类型对消息进行修改，切记这里只是示例，具体怎样对消息进行修改开发者可以根据自己的需求进行处理
                if (message.getSubType() == YWMessage.SUB_MSG_TYPE.IM_TEXT){
                    String content = message.getContent();
                    if (content.equals("55")) {
                        message.setContent("我修改了消息内容, 原始内容：55");
                        return message;
                    } else if (content.equals("66")){
                        YWMessage newMsg = YWMessageChannel.createTextMessage("我创建了一条新消息, 原始消息内容：66");
                        return newMsg;
                    } else if (content.equals("77")){
                        IMNotificationUtils.getInstance().showToast(getActivity(), "不发送该消息，消息内容为：77");
                        return null;
                    }
                }
                return message;
            }

            /**
             * 发送消息结束后回调
             * @param message   当前发送的消息
             * @param sendState 消息发送状态，具体状态请参考{@link com.alibaba.mobileim.conversation.YWMessageType.SendState}
             */
            @Override
            public void onMessageLifeFinishSend(YWMessage message, YWMessageType.SendState sendState) {

                IMNotificationUtils.getInstance().showToast(getActivity(), sendState.toString());
            }
        };
        mConversationService.setMessageLifeCycleListener(mMessageLifeCycleListener);
    }



    //设置连接状态的监听
    private void addConnectionListener() {
        mConnectionListener = new IYWConnectionListener() {
            @Override
            public void onDisconnect(int code, String info) {
                if (code == YWLoginCode.LOGON_FAIL_KICKOFF) {
                    //在其它终端登录，当前用户被踢下线
                    Toast.makeText(MyApplication.instatnce, "被踢下线", Toast.LENGTH_LONG).show();
                    YWLog.i("LoginSampleHelper", "被踢下线");
                    LoginSampleHelper.getInstance().setAutoLoginState(YWLoginState.idle);
                    getActivity().finish();
                    Intent intent = new Intent(MyApplication.instatnce, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    getActivity().startActivity(intent);
                }
            }

            @Override
            public void onReConnecting() {

            }

            @Override
            public void onReConnected() {

            }
        };
        mIMKit.getIMCore().addConnectionListener(mConnectionListener);
    }

    private void setSendMessageToContactInBlackListListener(){
        mSendMessageToContactInBlackListListener = new IYWSendMessageToContactInBlackListListener() {
            /**
             * 是否发送消息给黑名单中的联系人，当用户发送消息给黑名单中的联系人时我们会回调该接口
             * @param conversation 当前发送消息的会话
             * @param message      要发送的消息
             * @return true：发送  false：不发送
             */
            @Override
            public boolean sendMessageToContactInBlackList(YWConversation conversation, YWMessage message) {
                //TODO 开发者可用根据自己的需求决定是否要发送该消息，SDK默认不发送
                return true;
            }
        };
        mConversationService.setSendMessageToContactInBlackListListener(mSendMessageToContactInBlackListListener);
    }


    @Override
    public void update(Observable o, Object arg) {

        ResultEntity result = handlerError(arg);
        if (result!=null){

            if (result.getEventType()== BranchAddressPresenter.By_Alibaichuan_sync_success){
//                MAlert.alert("用户头像同步成功");

            }else if (result.getEventType()== BranchAddressPresenter.By_Alibaichuan_sync_fail){
//                MAlert.alert("用户头像同步失败");

            }
        }
    }
}
